import axios from "axios"
import base from "./base"

let refresh = false, requests = [];
let axiosx = axios.create({
    baseURL: base.API_PREFIX,
    timeout: 5000
});
// token刷新  https://zhuanlan.zhihu.com/p/91569497
axiosx.interceptors.request.use(config => {
    console.log(config.url, "【浏览器请求前拦截】", config);
    const tokenObj = base.getToken();
    if (tokenObj.token) {
        config.headers[base.token] = tokenObj.token;
    }
    if (config.url.endsWith("/login") || config.url.endsWith("/refresh")) {
        return config
    }
    if (tokenObj.token && tokenObj.tokenExpireTime) {
        const now = Date.now();
        if (now >= tokenObj.tokenExpireTime) {
            if (!refresh) {
                refresh = true;
                axiosx.refreshToken().then((res) => {
                    if (res && res.data && res.data.authorization) {
                        const token = res.data.authorization;
                        requests.forEach(cb => cb(token));
                        requests = [];
                    }
                }).finally(() => refresh = false);
            }
            return new Promise((resolve) => {
                requests.push((token) => {
                    config.headers[base.token] = token;
                    resolve(config);
                })
            });
        }
    }
    // if (true) {
    //     return new Promise((resolve,reject) => {
    //         setTimeout(() => {
    //             console.log('执行定时');
    //             config.xx = 'xx';
    //             reject(config);
    //         }, 5000);
    //     });
    // }
    return config;
}, error => {
    console.log("【浏览器请求失败】", error);
    return Promise.reject(error);
});
axiosx.interceptors.response.use(res => {
    console.log(res.request.responseURL, "【服务器返回后拦截】", res);
    if (res.data.code === 403) {
        if (!base.logout) {
            base.clearToken();
            console.log("删除过期token，并跳转首页");
        }
        return Promise.reject();
    }
    return res;
}, error => {
    console.log("【服务器返回后出错】", error);
    // return Promise.resolve(error);
    return Promise.reject(error);
});
axiosx.refreshToken = () => {
    return axiosx.post("/base/refresh").then(res => {
        base.setToken(res);
        return Promise.resolve(res);
    });
};
export default axiosx;


